package template

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

type PaserFile struct {
	filePath string          // file信息
	s        strings.Builder // 模版内容
}

const (
	meta_file          = "file:"
	meta_start         = "----"
	meta_end           = "----"
	eof_start          = "```"
	eof_end            = "```"
	replace_flag_start = "{{"
	replace_flag_end   = "}}"
)

// 解析模版文件
func paserTemplateFile(tplPath string) (tf PaserFile, err error) {
	file, err := os.Open(tplPath)
	if err != nil {
		fmt.Printf("打开文件时出错: %v\n", err)
		return tf, err
	}
	defer file.Close()

	// 创建 Scanner 对象
	scanner := bufio.NewScanner(file)

	// 逐行读取文件
	lineNumber := 1
	mode := 0
	for scanner.Scan() {
		line := scanner.Text() // 获取当前行的内容
		lineNumber++

		// 模版元信息开启标记
		if mode == 0 {
			if strings.HasPrefix(line, meta_start) {
				mode = 1
				continue
			}
		}

		// 提取模版元信息
		if mode == 1 {
			// 模版元信息截止标记
			if strings.HasPrefix(line, meta_end) {
				mode = 2
				continue
			}

			// 获取`file`元信息
			if strings.HasPrefix(line, meta_file) {
				tf.filePath = strings.TrimSpace(line[len(meta_file):])
			}
		}

		// 提取模版内容
		if mode == 2 {
			// 开启内容提取
			if strings.HasPrefix(line, eof_start) {
				mode = 3
				continue
			}
		}

		// 提取模版内容
		if mode == 3 {
			// 结束内容提取
			if strings.HasPrefix(line, eof_end) {
				mode = 4
				continue
			}

			//模版内容
			tf.s.WriteString(line)
			tf.s.WriteString("\n")
		}
	}

	return tf, nil
}
